package com.jiexin.schedule;


import com.jiexin.common.Constant;
import com.jiexin.model.ErrorSyncChange;
import com.jiexin.service.ChangeTabService;
import com.jiexin.service.MailService;
import com.jiexin.service.ResultTabService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: Jay_Liu
 * @Description: 将基础数据解析成结果表数据的计划事件
 * @Trigger：
 * @Date: Created in 14:57 2019/3/4
 * @Modified By:
 */
@Component
@Slf4j
public class TransferToResultTab {

    @Resource
    private ChangeTabService changeTabService;

    @Resource
    private ResultTabService resultTabService;

    @Resource
    private MailService mailService;

    @Value("${dshMailSubject}")
    private String dshMailSubject;

    @Value("${catMailSubject}")
    private String catMailSubject;

    @Scheduled(cron="*/50 * * * * ?")
    public void transferDSHResultTab() {
        Integer pid = null;
        try {
            //Detect Mail
            ErrorSyncChange errorSyncChange = changeTabService.dshDetectErrorSyncChange();
            if (errorSyncChange != null) {
                log.info("[DSH] begin detecting change with error sync state to send mail,current pid is:{}", errorSyncChange.getPid());
                String mailSubject = dshMailSubject + " " +errorSyncChange.getChangeNumber();
                String mailMsg = TransferToResultTab.combineMailMsg(errorSyncChange);
                mailService.sendMail("", mailSubject , mailMsg);
                changeTabService.updateDSHMailStateForChange(errorSyncChange.getPid(), Constant.SUCCESS_FLAG);
                log.info("[DSH] end detecting change with error sync state to send mail ,current pid is:{}", errorSyncChange.getPid() );
            }
            //Execute Procedure
            pid = changeTabService.findDSHNotTransferredChange();
            log.info("[DSH] begin transferring data to DSH Result Table,current pid is:{}", pid);
            if (pid == null) {
                log.info("[DSH] no data needs to be transferred to DSH Result Table");
                return;
            }
            resultTabService.executeDSHResultTabProce(pid);
            changeTabService.updateDSHSyncMsgForChange(pid, Constant.SUCCESS_FLAG, Constant.SUCCESS_MSG);

        } catch (Exception e) {
            changeTabService.updateDSHSyncMsgForChange(pid, Constant.FAILURE_FLAG, e.getMessage());
            log.error("[DSH] execute DSH Result Table Procedure error:{}", e);
        }
        log.info("[DSH] end transferring data to DSH Result Table,current pid is :{}", pid);
    }

    @Scheduled(cron="*/60 * * * * ?")
    public void transferCATResultTab() {
        Integer pid = null;
        try {
            //Detect Mail
            ErrorSyncChange errorSyncChange = changeTabService.catDetectErrorSyncChange();
            if (errorSyncChange != null) {
                log.info("[CAT] begin detecting change with error sync state to send mail,current pid is:{}", errorSyncChange.getPid());
                String mailSubject = catMailSubject + errorSyncChange.getChangeNumber();
                String mailMsg = TransferToResultTab.combineMailMsg(errorSyncChange);
                mailService.sendMail("", mailSubject , mailMsg);
                changeTabService.updateCATMailStateForChange(errorSyncChange.getPid(), Constant.SUCCESS_FLAG);
                log.info("[CAT] end detecting change with error sync state to send mail ,current pid is:{}", errorSyncChange.getPid() );
            }
            //Execute Procedure
            pid = changeTabService.findCATNotTransferredChange();
            log.info("[CAT] begin transferring data to CAT Result Table,current pid is:{}", pid);
            if (pid == null) {
                log.info("[CAT] no data needs to be transferred to CAT Result Table");
                return;
            }
            resultTabService.executeCATResultTabProce(pid);
            changeTabService.updateCATSyncMsgForChange(pid, Constant.SUCCESS_FLAG, Constant.SUCCESS_MSG);

        } catch (Exception e) {
            changeTabService.updateCATSyncMsgForChange(pid, Constant.FAILURE_FLAG, e.getMessage());
            log.error("[CAT] execute CAT Result Table Procedure error:{}", e);
        }
        log.info("[CAT] end transferring data to DSH Result Table,current pid is:{}", pid);
    }

    /**
     * parse object as a mail message content
     * @param errorSyncChange
     * @return
     */
    public static String combineMailMsg (ErrorSyncChange errorSyncChange) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[Change Number]:" + errorSyncChange.getChangeNumber());
        stringBuilder.append("\n[Description]:" + errorSyncChange.getDescription());
        stringBuilder.append("\n[Reason]:" + errorSyncChange.getReason());
        stringBuilder.append("\n[Create User]:" + errorSyncChange.getCreateUser());
        stringBuilder.append("\n[PID]:" + errorSyncChange.getPid());
        stringBuilder.append("\n[Error Msg]:" + errorSyncChange.getSyncMessage());
        stringBuilder.append("\nPlease contact the administrator ");
        return stringBuilder.toString();
    }

}
